<template>
  <el-scrollbar ref="scrollbarRef">
    <div class="main">
      <div class="userInfo right" style="margin-top: 20px; font-size: 14px">
        <span>
          成绩：
          {{ userInfo.sgname + ' ' + userInfo.score + '分' }}
          <el-icon
            class="curr"
            color="#004cf7"
            size="12"
            @click="onClickUpdateScore"
          >
            <EditPen />
          </el-icon>
        </span>
        <span style="margin: 0 35px">
          <el-popover
            placement="bottom"
            :width="248"
            :visible="showbatchPopover"
          >
            <template #reference>
              <el-button
                text="plain"
                @click.stop="showbatchPopover = !showbatchPopover"
                >{{ batchData.batch }}
                <el-icon size="13">
                  <ArrowDownBold />
                </el-icon>
              </el-button>
            </template>
            <el-table
              :show-header="false"
              :header-cell-style="{
                backgroundColor: '#f5f5f5',
                color: '#333',
                'font-weight': '500',
                'text-align': 'center',
              }"
              :cell-style="{ 'text-align': 'center' }"
              border
              :data="batchDatas"
            >
              <el-table-column prop="batch" width="74" />
              <el-table-column prop="score" width="74" />
              <el-table-column width="74">
                <template #default="spoce">
                  <el-button
                    style="color: red"
                    link
                    @click="onClickFillVolunteer(spoce.$index)"
                    >填报</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-popover>
        </span>
        <span class="curr" @click="onClickMyVolunteerList">
          <span>我的志愿表</span>
          (<span style="color: #004cf7">{{ volunteerTotal }}</span
          >)
        </span>
      </div>

      <div class="cloum flexcenter" style="padding: 30px 0">
        <!-- <el-button @click="oneClickToFillIn">一键填报</el-button> -->

        <mycanvas @handleGoDetails="handleGoDetails" :screenNum="screenNum" />

        <el-button
          style="
            margin: 50px 0 0 0;
            color: var(--color-text);
            border: 1px solid var(--color-text);
          "
          @click="showScreenView = !showScreenView"
        >
          个性化设置&nbsp;
          <el-icon>
            <ArrowUp v-if="showScreenView" />
            <ArrowDown v-else />
          </el-icon>
        </el-button>
        <div v-show="screenNum > 0" class="screen-num">{{ screenNum }}</div>
      </div>
      <div
        v-show="showScreenView"
        class="box-card"
        style="margin-top: 10px"
        @click="((showScreenPopover = false), (showbatchPopover = false))"
      >
        <!--院校/专业/职业-->
        <div class="alitem between" style="padding: 15px 13px 0">
          <div class="alitem">
            <div
              style="margin: 0 10px"
              v-for="(item, idx) in tabslist"
              :key="idx"
              :class="item.id === index ? 'active' : 'tabs'"
              @click="index = idx"
            >
              {{ item.name }}
            </div>
          </div>
        </div>
        <div v-show="index == 0">
          <schoolDate ref="schoolDateinfo"></schoolDate>
        </div>
        <div v-show="index == 1">
          <specialty ref="majorDataInfo" :batchInfo="batchData"></specialty>
        </div>
        <div v-show="index == 2">
          <career ref="jobDataInfo"></career>
        </div>
        <!--筛选条件-->
        <div class="screen matop between">
          <div class="screenSize" style="width: 65px">筛选条件:</div>
          <div class="flexwrap" style="width: 100%">
            <div
              class="screenTab between flexwrap"
              v-for="(item, idx) in userSearchDate"
              @click="delChange(idx, item)"
            >
              {{ item.name }}
              <el-icon size="12" style="margin-left: 2px; cursor: pointer">
                <Close />
              </el-icon>
            </div>
          </div>
          <div class="curr" style="width: 70px">
            <el-icon
              size="14"
              style="width: 60px"
              @click="onClickDeleteAllSearch"
            >
              <Delete /> 清空
            </el-icon>
          </div>
        </div>
        <!-- 筛选信息 -->
        <el-popover
          placement="bottom"
          :width="300"
          :visible="showScreenPopover"
        >
          <template #reference>
            <el-button
              style="margin: 10px 5px"
              text="plain"
              @click.stop="showScreenPopover = !showScreenPopover"
              >高级筛选
              <el-icon size="15">
                <ArrowDownBold />
              </el-icon>
            </el-button>
          </template>
          <el-form
            ref="ruleFormRef"
            label-position="top"
            :model="requestData"
            label-width="auto"
          >
            <el-form-item label="中外合作">
              <el-radio-group v-model="fType">
                <el-radio :label="0">全部</el-radio>
                <el-radio :label="1">仅看中外</el-radio>
                <el-radio :label="2">不看中外</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="历年征集">
              <el-radio-group v-model="hasZJ">
                <el-radio :label="0">全部</el-radio>
                <el-radio :label="1">仅看征集</el-radio>
                <el-radio :label="2">不看征集</el-radio>
              </el-radio-group>
            </el-form-item>
            <div class="right">
              <el-button @click="resetForm()">重置</el-button>
              <el-button type="primary" @click="submitForm()"> 确定 </el-button>
            </div>
          </el-form>
        </el-popover>
      </div>

      <div style="font-size: 14px; padding-bottom: 100px">
        <h3>推荐原理及说明：</h3>
        <p>
          依据考生成绩，并结合用户关注过的、填报过的、浏览过的院校、专业、职业为画像及个性化设置要求，配合专业定位测评及院校、专业热门指数，按冲、稳、保规则录取概率从小到大排序生成个性化的志愿表。苛刻的个性化设置条件可能会导致志愿表生成数量过少的情况，建议扩大设置范围。
        </p>
        <p>
          注意：一键填报生成的志愿表仅用于模拟参考，建议考生依据自身条件和需求再此基础上修改调整出符合自己的最终方案。
        </p>
      </div>
    </div>
  </el-scrollbar>
  <!--用户修改信息-->
  <userUpdate
    ref="userUpdatesRef"
    @refreshStudentList="pagination"
  ></userUpdate>
  <reportDialog ref="report"></reportDialog>
  <!-- 不是会员弹窗 -->
  <el-dialog
    ref="isVipDialog"
    v-model="dialogVisible"
    title=""
    width="30%"
    :before-close="cancel"
    center
  >
    <div class="dialog-content">
      <WarningFilled class="icon-WarningFilled" />
      <span>开通VIP无限使用</span>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleClose(true)">
          开通vip
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { reactive, ref, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
import {
  zyList,
  batchInfo,
  schoolEnrollChance,
} from '@/api/volunteer/volunteer';
import schoolDate from '@/views/volunteer/components/schoolDate.vue'; // 学校
import career from '@/views/volunteer/components/career.vue'; // 职业
import specialty from '@/views/volunteer/components/specialty.vue'; // 专业
import userUpdate from '@/views/volunteer/components/userUpdate.vue';
import reportDialog from '@/views/volunteer/components/reportDialog.vue';
import mycanvas from './components/Mycanvas';
import { ElMessage, ElMessageBox } from 'element-plus';

const store = useStore();
const userSearchDate = computed(() => store.getters.tianbao.searchArraylist); // 筛选数据
const isVIP = computed(() => store.getters.user.userInfo.isVIP); // 是否是vip
const userInfo = store.getters.user.userInfo; // 用户信息
const dialogVisible = ref(false);
const schoolDateinfo = ref(null);
const majorDataInfo = ref(null);
const jobDataInfo = ref(null);
const router = useRouter();
const route = useRoute();
const report = ref(null);
const tabslist = ref([
  { id: 0, name: '院校优先' },
  { id: 1, name: '专业优先' },
  { id: 2, name: '职业优先' },
]);

const index = ref(0);
const scrollbarRef = ref(null);
const userUpdatesRef = ref(null);
const selTypeIndex = ref(0); // 选中的填报类型 0-专业/院校 or 1-院校/专业 山东填报类型或北京专科填报类型才会显示
const batchData = ref({}); // 选择的批次线信息
const batchDatas = ref([]); // 批次线信息数组
// 请求数据
const requestData = reactive({
  // batch: '',
  // fronttype: 3,
  auto: 1,
  fType: 0, // 中外合作 0-全部
  hasZJ: 0, // 历年征集 0-全部
});

const fType = ref(0);
const hasZJ = ref(0);

const screenData = ref({}); // 筛选数据
const isRequest = ref(false);
const showScreenView = ref(false); // 是否显示筛选视图
const showbatchPopover = ref(false); // 是否显示批次弹窗
const showScreenPopover = ref(false); // 是否显示高级筛选弹窗
const volunteerTotal = ref(0); // 志愿表总数
const screenNum = ref(0); // 筛选条件总数

watch(
  // 监听院校筛选数据改变
  () => userSearchDate.value,
  () => {
    // console.log('筛选条件改变', userSearchDate.value)
    savelocalStorage();
    schoolSearchDataChange();
  },
);

initSource();

function initSource() {
  let schoolArrayList =
    JSON.parse(localStorage.getItem('schoolArrayList')) || [];
  let majorArrayList = JSON.parse(localStorage.getItem('majorArrayList')) || [];
  let jobArrayList = JSON.parse(localStorage.getItem('jobArrayList')) || [];
  let advancedList = JSON.parse(localStorage.getItem('advancedList')) || [];

  // 初始化本地高级筛选条件
  advancedList.forEach((item) => {
    if (item.type == 'fType') {
      fType.value = item.code;
      requestData.fType = item.code;
    } else {
      hasZJ.value = item.code;
      requestData.hasZJ = item.code;
    }
  });

  store.dispatch('tianbao/saveSchoolInfoChange', schoolArrayList);
  store.dispatch('tianbao/saveMajorInfoChange', majorArrayList);
  store.dispatch('tianbao/saveJobInfoChange', jobArrayList);
  store.dispatch('tianbao/saveAdvancedInfoChange', advancedList);

  screenNum.value =
    schoolArrayList.length +
    majorArrayList.length +
    jobArrayList.length +
    advancedList.length;
}

// 保存筛选信息到本地
function savelocalStorage() {
  let schoolArrayList = store.getters.tianbao.schoolArrayList; // 学校
  let majorArrayList = store.getters.tianbao.majorArrayList; // 专业
  let jobArrayList = store.getters.tianbao.jobArrayList; // 职业
  let advancedList = store.getters.tianbao.advancedList; // 高级

  screenNum.value =
    schoolArrayList.length +
    majorArrayList.length +
    jobArrayList.length +
    advancedList.length;

  localStorage.setItem('schoolArrayList', JSON.stringify(schoolArrayList));
  localStorage.setItem('majorArrayList', JSON.stringify(majorArrayList));
  localStorage.setItem('jobArrayList', JSON.stringify(jobArrayList));
  localStorage.setItem('advancedList', JSON.stringify(advancedList));
}

// 院校筛选数据改变
function schoolSearchDataChange() {
  let searchData = {
    province: [],
    categories: [],
    features: [],
    natureType: [],
    eduLevelSchool: [],
    schoolNewly: [],
    scode: [],
    mcode: [],
    zcode: [],
    ssearch: '',
    msearch: '',
    zsearch: '',
  };

  for (let item of userSearchDate.value) {
    switch (item.type) {
      case 'province':
        searchData.province.push(item.code);
        break;
      case 'type':
        searchData.categories.push(item.code);
        break;
      case 'school_feature':
        searchData.features.push(item.code);
        break;
      case 'nature':
        searchData.natureType.push(item.code);
        break;
      case 'school_type':
        searchData.eduLevelSchool.push(item.code);
        break;
      case 'schoolNewly':
        searchData.schoolNewly.push(item.code);
        break;
      case 'schoolSearch':
        searchData.scode.push(item.code);
        break;
      case 'major':
        searchData.mcode.push(item.code);
        break;
      case 'job':
        searchData.zcode.push(item.code);
        break;
      case 'ssearch':
        searchData.ssearch = item.name;
        break;
      case 'msearch':
        searchData.msearch = item.name;
        break;
      case 'zsearch':
        searchData.zsearch = item.name;
    }
  }

  let data = {
    province: searchData.province.toString(),
    categories: searchData.categories.toString(),
    features: searchData.features.toString(),
    natureType: searchData.natureType.toString(),
    eduLevelSchool: searchData.eduLevelSchool.toString(),
    schoolNewly: searchData.schoolNewly.toString(),
    scode: searchData.scode.toString(),
    mcode: searchData.mcode.toString(),
    zcode: searchData.zcode.toString(),
    ssearch: searchData.ssearch,
    msearch: searchData.msearch,
    zsearch: searchData.zsearch,
  };
  // console.log('---data---', data)
  screenData.value = data;
}

init();
// 初始化
function init() {
  let data = JSON.parse(route.query.data);
  batchData.value = data.batchInfo;
  requestData.batch = batchData.value.batch;

  if (!data.update) {
    // 重置仓库中志愿表数据
    // volunteerStore.setVolunteerInfos([])
    store.dispatch('tianbao/setVolunteerInfos', []);
  }

  // 设置一键填报
  localStorage.setItem('isYJTB', 1);

  getZyList();
  getBatchInfo();
}

// 获取志愿表列表
function getZyList() {
  zyList({ page: 0, pageSize: 0 }).then((res) => {
    // console.log(res)
    volunteerTotal.value = res.data.data.count;
  });
}

// 获取批次线信息
function getBatchInfo() {
  let body = { pid: userInfo.pid, course: userInfo.course, less: 1 };
  batchInfo(body).then((res) => {
    // console.log('---批次线信息---', res)
    batchDatas.value = res.data.data.batches;
  });
}

/**
 * 获取填报列表
 * @param {Object} page 页码 可选参数，用于page=1
 */
function getSchoolEnrollChance() {
  if (screenNum.value > 20) {
    ElMessage({ type: 'warning', message: '筛选的数量不能超过20个' });
    return;
  }

  let data = { ...requestData, ...screenData.value };

  if (selTypeIndex.value == 1) {
    data['zy_type'] = 3;
  }

  if (isRequest.value) return;
  isRequest.value = true;
  data['score'] = userInfo.score; //成绩
  data['sgid'] = convertString(userInfo.sgname);
  data['course'] = localStorage.getItem('courseNew');
  schoolEnrollChance(data)
    .then((res) => {
      if (res.code == 44444) {
        ElMessage.error(res.msg);
        router.go(-1);
      } else {
        localStorage.setItem(
          'courseNew',
          res.data.data?.scoreConfigData?.course
            ? res.data.data.scoreConfigData.course
            : '',
        );
        isRequest.value = false;
        const data = res.data.data || {};

        if (data.list.length > 0) {
          if (data.zy_info.zy_type == 3) {
            // 四川
            // let volunteersInfo = [];
            data.list.forEach((item, index) => {
              // 将hash值转换为大写英文字母
              let key = String.fromCharCode(index + 65);
              item.vkey = key;
            });

            localStorage.setItem('volunteerInfos', JSON.stringify(data.list));
            localStorage.setItem(
              'equivalents',
              JSON.stringify(data.equivalents),
            );
          } else {
            localStorage.setItem('volunteerInfos', JSON.stringify(data.list));
          }

          let body = {
            batchData: batchData.value,
            zy_type: data.zy_info.zy_type,
            year: data.summary.today_year,
          };
          router.push({
            path: '/tempVolunteer',
            query: { data: JSON.stringify(body) },
          });
        } else {
          ElMessage({
            type: 'warning',
            message:
              '符合条件的院校或专业太少，无法生成志愿表，建议您调整”个性化设置“条件！',
          });
        }
      }
    })
    .catch(() => {
      isRequest.value = false;
    });
}

// 点击修改分数
function onClickUpdateScore() {
  userUpdatesRef.value.openChange();
}

// 点击我的志愿表
function onClickMyVolunteerList() {
  router.push({ path: '/volunteerList' });
}

/**
 * 点击填报切换批次
 * @param {Number} index 下标
 */
function onClickFillVolunteer(index) {
  let batch = batchDatas.value[index];
  if (batchData.value.id != batch.id) {
    showbatchPopover.value = false;
    ElMessageBox.confirm(
      '切换批次后，上次填报院校以及专业全部清空',
      '是否切换当前批次,当前批次' + batchData.value.batch,
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' },
    ).then(() => {
      // 更新批次信息
      batchData.value = batchDatas.value[index];
      requestData.batch = batchData.value.batch;
      // 清空筛选条件
      onClickDeleteAllSearch();
    });
  }
}

// 点击一键填报
function handleGoDetails() {
  if (isVIP.value != 0) {
    getSchoolEnrollChance();
  } else {
    dialogVisible.value = true;
  }
}

// 删除单个筛选数据
function delChange(idx, item) {
  // console.log(idx, item)
  if (item.type == 'major' || item.type == 'msearch') {
    // 专业
    majorDataInfo.value.deleteScreenItem(item);
  } else if (item.type == 'job' || item.type == 'zsearch') {
    // 职业
    jobDataInfo.value.deleteScreenItem(item);
  } else if (item.type == 'fType' || item.type == 'hasZJ') {
    // 高级
    item.type == 'fType' ? (fType.value = 0) : (hasZJ.value = 0);
    submitForm();
  } else {
    // 院校
    schoolDateinfo.value.deleteScreenItem(item);
  }
}

// 删除全部筛选数据
function onClickDeleteAllSearch() {
  if (userSearchDate.value.length > 0) {
    requestData.fType = 0;
    requestData.hasZJ = 0;
    fType.value = 0;
    hasZJ.value = 0;
    majorDataInfo.value.deleteAll();
    jobDataInfo.value.deleteAll();
    schoolDateinfo.value.deleteAll();
    store.dispatch('tianbao/saveAdvancedInfoChange', []);
  }
}

function submitForm() {
  if (requestData.fType != fType.value || requestData.hasZJ != hasZJ.value) {
    requestData.fType = fType.value;
    requestData.hasZJ = hasZJ.value;

    let arr = [];
    if (requestData.fType != 0) {
      arr.push({
        name: requestData.fType == 1 ? '仅看中外' : '不看中外',
        code: requestData.fType,
        type: 'fType',
      });
    }

    if (requestData.hasZJ != 0) {
      arr.push({
        name: requestData.hasZJ == 1 ? '仅看征集' : '不看征集',
        code: requestData.hasZJ,
        type: 'hasZJ',
      });
    }

    // userSearchVal.saveAdvancedInfoChange(arr)
    store.dispatch('tianbao/saveAdvancedInfoChange', arr);
    showScreenPopover.value = false;
  }
}

// 重置高级筛选
function resetForm() {
  fType.value = 0;
  hasZJ.value = 0;
}

// 判断会员弹窗
// 点击取消
const cancel = () => {
  dialogVisible.value = false;
  ElMessage({ message: '已取消' });
};
// 点击确定
const handleClose = () => {
  // 跳转到开通会员页面，应该是会员商品的详情
  router.push({
    path: '/shopserve/shopDet',
    query: { id: store.getters.indexInfo.vipserviceid },
  });
};
</script>

<style lang="scss" scoped>
.classifyheader {
  position: sticky;
  top: 0;
  z-index: 99;
  background: #fafafa;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  color: #86909c;
  letter-spacing: 0;
  line-height: 28px;
  padding-right: 80px;

  .sort-sel {
    color: #004cf7;
  }
}

.screen {
  min-height: 50px;
  padding: 6px 0 6px 20px;
  background-color: #f9f9f9;
  display: flex;
  overflow: hidden;
  align-items: center;

  .screenSize {
    font-size: 12px;
    font-weight: 400;
    color: #3d3d3d;
    width: 55px;
  }

  .screenTab {
    padding: 7px 10px;
    margin: 2px 0;
    background: #fff;
    border: 1px solid #e6e6e6;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 400;
    color: #4e5969;
    line-height: 14px;
    margin-left: 10px;
  }
}

.box-card {
  margin-bottom: 30px;
  border: #e6e6e6 1px solid;
  // height: calc(100vh - 100px);
  // overflow-y: auto;

  .tabs {
    color: #000000;
    font-weight: 600;
    cursor: pointer;
  }

  .active {
    color: #004cf7;
    font-weight: 600;
    cursor: pointer;
  }

  .card-header {
    font-size: 20px;
    font-weight: 600;
    color: #1d2129;
    padding: 10px;

    .userInfo {
      margin-left: 30px;
      font-size: 16px;
      font-weight: 400;
      color: #1d2129;
      line-height: 16px;

      span {
        margin-left: 8px;
      }
    }

    .headerSize {
      color: #4e5969;
      font-size: 14px;
      margin-left: 12px;
      font-weight: 400;
      height: 20px;
      line-height: 21px;
    }
  }
}

.screen-num {
  text-align: center;
  line-height: 20px;
  font-size: 14px;
  background-color: #004cf7;
  color: white;
  border-radius: 10px;
  height: 20px;
  min-width: 30px;
  margin-left: 115px;
  margin-top: -40px;
}

.dialog-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .icon-WarningFilled {
    width: 10em;
    height: 10em;
    color: var(--color-text);
  }

  span {
    display: inline-block;
    height: 2em;
    line-height: 4em;
    font-size: 1.5em;
    color: var(--color-text);
    margin: 30px 0;
  }
}

.dialog-footer {
  button {
    border-radius: 20px;
    width: 170px;
    height: 40px;
    line-height: 40px;
    margin: auto;
    cursor: pointer;
    border: none;
    background: var(--background-color);
    background-color: var(--background-color);
  }
}
</style>
